package com.mezz.bones.framework.outbox.executor.impl;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.mezz.bones.framework.outbox.domain.entity.OutboxMessage;
import com.mezz.bones.framework.outbox.executor.MessageExecutor;
import com.mezz.bones.framework.outbox.model.ExecuteResult;
import lombok.AllArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanNameGenerator;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @Author: zhuang
 * @Date: 2025/4/29 9:56
 * @Description: TODO
 * @Version: 1.0
 **/

@Component
@AllArgsConstructor
public class BeanMessageExecutor implements MessageExecutor {

    private final ApplicationContext context;

    @Override
    public ExecuteResult execute(OutboxMessage message) {
        try {
            Object bean = context.getBean(message.getExecuteTarget());
            Method method = bean.getClass().getMethod(
                    message.getExecuteMethod(),
                    String.class); // 统一传消息内容

            Object result = method.invoke(bean, message.getExecuteParams());
            return ExecuteResult.ok(result);
        } catch (Exception e) {
            return ExecuteResult.error(e.getMessage(), ExceptionUtil.stacktraceToString(e));
        }
    }

    @Override
    public String tag() {
        return TAG_BEAN;
    }

}
